<script setup lang="ts">
import { TreeSelectProps } from '../type';

const props = withDefaults(defineProps<TreeSelectProps>(), {
	multiple: false,
	placeholder: '请选择',
	options: () => [],
	value: () => '',
});

const emit = defineEmits<{
	(e: 'update:value', value: string | string[]): void;
}>();

defineOptions({
	name: 'QTreeSelect',
	inheritAttrs: false,
});

const selectedKeys = ref<string[]>(Array.isArray(props.value) ? props.value : props.value ? [props.value] : []);
const showPopover = ref(false);

const selectedLabels = computed(() => {
	return selectedKeys.value
		.map((key) => {
			const findNode = (nodes: any[], targetKey: string): any => {
				for (const node of nodes) {
					if (node.key === targetKey) return node;
					if (node.children?.length) {
						const found = findNode(node.children, targetKey);
						if (found) return found;
					}
				}
				return null;
			};
			const node = findNode(props.options, key);
			return node?.label || '';
		})
		.filter(Boolean)
		.join(', ');
});

const handleSelect = (keys: string[]) => {
	console.log(keys);
	selectedKeys.value = keys;
	emit('update:value', props.multiple ? keys : keys[0] || '');
	showPopover.value = false;
};

const handleClear = (e: MouseEvent) => {
	e.stopPropagation();
	selectedKeys.value = [];
	emit('update:value', props.multiple ? [] : '');
};
</script>

<template>
	<n-popover trigger="click" v-model:show="showPopover" placement="bottom">
		<template #trigger>
			<n-input readonly :placeholder="placeholder" :value="selectedLabels" clearable @clear="handleClear">
				<template #suffix>
					<i class="icon-[ant-design--caret-down-outlined]" />
				</template>
			</n-input>
		</template>

		<div class="max-h-[300px] min-w-[200px] overflow-auto">
			<n-tree block-line :data="options" selectable :expand-on-click="true" v-bind="$attrs"  />
		</div>
	</n-popover>
</template>

<style scoped>
.n-input {
	min-width: 200px;
}
</style>
